import axios from "axios";
import config from "@/config";
import nprogress from "nprogress";
import store from "@/store/index";
import router from "@/router";
import { Toast } from "vant";

const request = axios.create({
  baseURL: config.baseUrl,
  timeout: config.timeout,
  withCredentials:true
});

request.interceptors.request.use((config) => {
  nprogress.start();
  config.headers["token"] = store.state.user.token;
  config.headers["Content-Type"] = "application/json";
  return config;
});

request.interceptors.response.use((res) => {
  // console.log("Response: ", res.data);
  nprogress.done();
  if (res.data.code === 403 || res.data.message === "authentication failed" ) {
    Toast("登录态过期");
    store.dispatch("user/setToken", "");
    store.dispatch("user/setUserInfo", {});
    localStorage.removeItem("token");
    localStorage.removeItem("userInfo");
    router.replace("/login");
  }
  return res.data;
});

export default request;
